import { TAllTypes, IValue, IValueNumber } from '../../types';
import { AFunc, IPositionValue } from '../types';
import { calculate } from '../../calculate';
import { parseToNumber } from '../../utils';
export class Average extends AFunc {
  protected avalidateVals(val: TAllTypes): IValueNumber[] {
    if(val.type === 'value') {
      if(val.dataType === 'number') {
        return [val];
      }
      if(val.dataType === 'string' && !isNaN(Number(val.value))) {
        return [parseToNumber(val)];
      }
    }
    if(val.type === 'position' || val.type === 'rowPosition' || val.type === 'colPosition') {
      let _val = this.positionVal.getValue(val);
      let res: IValueNumber[] = [];
      for(let item of _val) {
        res = res.concat(this.avalidateVals(item))
      }
      return res;
      
    }
    if(val.type === 'range') {
      let _val = val.value.getValues();
      let res: IValueNumber[] = [];
      for(let item of _val) {
        res = res.concat(...this.avalidateVals(item));
      }
      return res;
    }
    return [];
  }
  public excute(args: TAllTypes[]): TAllTypes[] {
    let vals: IValueNumber[] = [];
    for(let item of args) {
      vals = vals.concat(...this.avalidateVals(item))
    }
    if(vals.length === 0) {
      return [{type: 'value', dataType: 'number', value: 0}];
    }
    let sum: IValueNumber = {type: 'value', dataType: 'number', value: 0};
    for(let item of vals) {
      sum = calculate('+', [sum, item]) as IValueNumber;
    }
    let result = calculate('/', [sum, {type: 'value', dataType: 'number', value: vals.length}]);
    return [result];
  }
}